<template>

  <div v-if="fileList.length <=0 && !loading" style="height: 100%;">
    <el-empty description="啊偶~啥都木有"></el-empty>
  </div>

  <div v-else style="height: 100%;">
    <div class="table" v-if="style == 'table'">
      <el-skeleton :rows="15" animated v-if="loading"/>
      <div v-else>
        <el-table
            ref="ElTable"
            :data="fileList"
            tooltip-effect="dark"
            max-height="700"
            style="width: 100%"
            @select="handleSelectionChange"
            @select-change="handleSelectionChange"
        >
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              width="75"
          >
            <template #default="scope">
              <img :src="require('@/assets/images/type/'+scope.row.filetype+'.png')" alt="" style="width: 100%;"
                   v-if="scope.row.filetype != 'image'">
              <img :src="scope.row.preview" alt="" style="width: 100%;" v-else>
            </template>
          </el-table-column>
          <el-table-column
              prop="name"
              label="文件名"
          >
            <template #default="scope">
              <div
                  v-if="((isMkdir  || isTouch) && scope.row.name == '')  || (isRename &&  selectFileNameMaps.indexOf(scope.row.name) > -1)">
                <el-input
                    v-model="newFileName"
                    @input="change($event)"
                    style="width: 80%">
                </el-input>
                <i class="el-icon-check" style="opacity: 0;"></i>
                <el-button icon="el-icon-check" circle size="small" v-if="isMkdir" @click="mkdir"></el-button>
                <el-button icon="el-icon-check" circle size="small" v-else-if="isTouch" @click="touch"></el-button>
                <el-button icon="el-icon-check" circle size="small" v-else @click="rename"></el-button>
                <el-button icon="el-icon-close" circle size="small" @click="cancleOpera"></el-button>
              </div>
              <div v-else>
                <el-link :underline="false" href="javacript:void(0);" v-if="scope.row.type == 'dir'"
                         @click="init(scope.row.name)">
                  {{ scope.row.name }}
                </el-link>
                <el-link :underline="false" href="javacript:void(0);" v-else @click="preview(scope.row)"
                         @dbclick="open(scope.row)">
                  {{ scope.row.name }}
                </el-link>
              </div>
            </template>
          </el-table-column>
          <el-table-column
              prop="format_size"
              label="文件大小"
              width="120"
          ></el-table-column>
          <el-table-column
              prop="format_mtime"
              label="文件修改时间"
              width="200"
          ></el-table-column>
        </el-table>
      </div>

    </div>

    <div class="grid" v-else>
      <el-space wrap v-if="loading" :loading="loading">
        <el-skeleton style="width: 120px" animated v-for="i in 8">
          <template #template>
            <el-skeleton-item
                variant="image"
                style="width: 120px; height: 120px;"
            />
            <div style="padding: 14px;">
              <el-skeleton-item variant="h3" style="width: 50%;"/>
              <div
                  style="display: flex; align-items: center; justify-items: space-between; margin-top: 16px; height: 16px;">
                <el-skeleton-item variant="text" style="margin-right: 16px;"/>
                <el-skeleton-item variant="text" style="width: 30%;"/>
              </div>
            </div>
          </template>
        </el-skeleton>
      </el-space>
      <el-space v-else wrap size="large" v-loading="loading">
        <el-card class="box-card" v-for="(item,index) in fileList" :key="index" shadow="hover" style="width: 100%;">
          <div class="grid-item">
            <div class="check-area" @click="selectFile(item)">
              <i class="el-icon-success" v-if="selectFileNameMaps.indexOf(item.name) > -1 "></i>
              <i class="el-icon-circle-check" v-else></i>
            </div>
            <div class="background-image" @click="init(item.name)" v-if="item.type == 'dir'">
              <img :src="require('@/assets/images/type/'+item.filetype+'.png')" alt="">
            </div>
            <div class="background-image" @dblclick="open(item)" v-else>
              <el-image
                  style="width: 100px; height: 100px"
                  :src="require('@/assets/images/type/'+item.filetype+'.png')"
                  v-if="item.filetype != 'image'"
                  @click.stop="preview(item)"
                  fit="cover"></el-image>
              <el-image
                  style="width: 100px; height: 100px"
                  :preview-src-list="previewImageList"
                  :src="item.preview"
                  v-else
                  fit="cover"></el-image>
              <!--            <img :src="require('@/assets/images/type/'+item.filetype+'.png')" alt=""  v-if="item.filetype != 'image'">
                          <img :src="item.preview" alt="" style="width: 100%;" v-else>-->
            </div>
            <div class="text">
              <div
                  v-if="((isMkdir  || isTouch) && item.name == '') || (isRename && selectFileNameMaps.indexOf(item.name) > -1)">
                <el-input
                    v-model="newFileName"
                    @input="change($event)" style="width: 65%;">
                </el-input>
                <i class="el-icon-check" v-if="isMkdir" @click="mkdir"
                   style="border: 1px solid #F2F6FC;margin-left: 10px;"></i>
                <i class="el-icon-check" v-else-if="isTouch" @click="touch" style="border: 1px solid #F2F6FC;"></i>
                <i class="el-icon-check" v-else @click="rename" style="border: 1px solid #F2F6FC;"></i>
                <i class="el-icon-close" @click="cancleOpera" style="border: 1px solid #F2F6FC;"></i>
              </div>
              <div v-else>
                <el-link :underline="false" v-if="item.type == 'dir'" @click="init(item.name)"
                         href="javacript:void(0);">
                  {{ item.name }}
                </el-link>
                <el-link :underline="false" v-else @click="preview(item)" @dbclick="open(item)"
                         href="javacript:void(0);">
                  {{ item.name }}
                </el-link>
              </div>
            </div>
          </div>
        </el-card>
      </el-space>
    </div>
  </div>


  <!--  移动、复制的文件夹弹出层-->
  <el-dialog
      title="请选择目标文件夹"
      width="30%"
      center
      v-model="showTreeDirFrame"
  >
    <template #default>
      <el-tree
          v-loading="loadingTreeDirList"
          :data="treeDirList"
          :props="defaultProps"
          ref="treeDirListDom"
          node-key="id"
          highlight-current
          show-checkbox
          empty-text="正在加载中"
          :default-expanded-keys="[10]"
          @check="selectTreeDir"
          accordion>
      </el-tree>
    </template>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="showTreeDirFrame = false">取 消</el-button>
      <el-button type="primary" @click="doOpera">确 定</el-button>
    </span>
    </template>
  </el-dialog>

  <!--  预览弹出层BEGIN-->
  <!--  MP4-->
  <el-dialog
      v-model="previewFrame"
      :title="previewOptions.name"
      destroy-on-close
      width="30%"
      top="5vh"
      :before-close="closePreviewFrame"
      v-if="previewOptions.filetype == 'video'"
  >
    <video-player class="video-player vjs-custom-skin"
                  ref="videoPlayer"
                  :playsinline="true"
                  :options="previewOptions"
    ></video-player>
  </el-dialog>

  <!--  图片-->
  <el-dialog
      v-model="previewFrame"
      :title="previewOptions.name"
      v-if="previewOptions.filetype == 'image'"
      destroy-on-close
      width="20%"
      top="5vh"
      :before-close="closePreviewFrame"
  >
    <el-image :src="previewOptions.preview" style="width: 100%;"></el-image>
  </el-dialog>
  <!-- mp3-->
  <el-dialog
      v-model="previewFrame"
      :title="previewOptions.name"
      v-if="previewOptions.filetype == 'mp3'"
      destroy-on-close
      width="20%"
      top="5vh"
      :before-close="closePreviewFrame"
  >
    <aplayer autoplay :audio="previewOptions"/>
  </el-dialog>

  <!--  代码编辑器-->
  <el-dialog
      v-model="previewFrame"
      :title="previewOptions.name"
      v-if="previewOptions.edit"
      destroy-on-close
      width="70%"
      height="50vh"
      top="5vh"
      :before-close="closePreviewFrame"
  >
    <MonacoEditor
        v-model="editorContent">
    </MonacoEditor>
  </el-dialog>
  <!-- 预览弹出层END-->

  <!--  分享文件的弹出层-->
  <el-dialog
      v-model="isShare"
      title="分享文件（夹）"
      width="30%"
      center
  >

    <el-form ref="form" label-width="80px">
      <el-form-item label="有效期">
        <el-select v-model="shareExpireTime">
          <el-option
              v-for="item in shareExpireOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
      <el-button @click="isShare = false">取 消</el-button>
      <el-button type="primary" @click="doShare">确 定</el-button>
    </span>
    </template>
  </el-dialog>
  <!--  分享文件弹出层END-->
</template>

<script>
import MonacoEditor from 'vue-monaco-editor'
import Audio from '../components/preview/Audio'
import Video from '../components/preview/Video'
import Editor from '../components/preview/Editor'
export default {
  name: "Layout",
  props: {
    style: {
      type: String,
      default: 'table'
    },
    currentType: {
      type: String,
      default: 'all'
    },
    currentPath: {
      type: Array,
      default: []
    }
  },
  watch: {    //监听
    style: {
      immediate: true,
      handler: function (value) {
        if (value == 'table' && this.checkedFiles.length > 0) {
          console.log(value, '1');
          this.$nextTick(() => { //此处使用这个可以等节点渲染后再获取节点
            this.checkedFiles.forEach(item => {
              this.$refs.ElTable.toggleRowSelection(item, true);
            });
          })
        }
        console.log(value, '2');

      }
    },
    currentType: {
      immediate: true,
      handler: function (value) {
        if (this.currentType != value && value != undefined) {
          this.currentType = value;
          this.init();
        }
      }
    }
  },
  components: {
    MonacoEditor,
    Audio,
    Video,
    Editor
  },
  data() {
    return {
      searchName: '',
      selectFileNameMaps: [],
      checkedFiles: [],
      currentFile: {},
      fileList: [],
      loading: false,
      isMkdir: false,
      isRename: false,
      isTouch: false,
      isShare: false,
      shareExpireTime: 0,
      shareExpireOptions: [
        {
          value: 0,
          label: '不限制',
        },
        {
          value: 1,
          label: '1天'
        },
        {
          value: 7,
          label: '7天'
        },
        {
          value: 30,
          label: '30天'
        },
      ],
      newFileName: '',//重命名
      operaName: '',
      showTreeDirFrame: false,
      loadingTreeDirList: false,
      treeDirList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      previewFrame: false,
      previewOptions: {},
      previewImageList: [],
      previewAudioList: [],
      previewVideoList: [],
      editorContent: '',
    }
  },
  created() {
    this.init();
  },
  methods: {
    handleSelectionChange(checked) {
      this.selectFileNameMaps = [];
      this.currentFile = {};
      if (checked.length == 1) {
        this.currentFile = checked[0];
        this.$emit('listenCurrentFile', this.currentFile);
      } else {
        this.$emit('listenCurrentFile', {});
      }
      checked.forEach(row => {
        this.selectFileNameMaps.push(row.name);
      })
      this.$emit('listenCheckedFiles', checked);
    },
    selectFile(file) {
      this.currentFile = {};
      let eq = this.selectFileNameMaps.indexOf(file.name);
      if (eq > -1) {
        this.checkedFiles.splice(eq, 1);
        this.selectFileNameMaps.splice(eq, 1);
      } else {
        this.checkedFiles.push(file);
        this.selectFileNameMaps.push(file.name);
      }

      if (this.checkedFiles.length == 1) {
        this.currentFile = this.checkedFiles[0];
        this.$emit('listenCurrentFile', this.currentFile);
      } else {
        this.$emit('listenCurrentFile', {});
      }
      this.$emit('listenCheckedFiles', this.checkedFiles);
    },
    init(path = '', sortField = 'size', sortMod = 'asc') {
      let that = this;
      that.previewImageList = that.previewAudioList = that.previewVideoList = [];
      that.loading = true;
      that.$axios.get('index/dir', {
        params: {
          currentPath: path,
          sort: sortField,
          type: that.currentType,
          sortMode: sortMod,
          name: that.searchName
        }
      }).then(res => {
        that.loading = false;
        that.fileList = res.data.data.list;
        that.fileList.forEach(row => {
          if (row.filetype == 'image') {
            that.previewImageList.push(row.preview);
          } else if (row.filetype == 'audio') {
            that.previewAudioList.push(row);
          } else if (row.filetype == 'video') {

          }
        })
        that.$emit('listenFileList', that.fileList)
        that.$emit('listenCurrentPath', res.data.data.currentPath)
      })
    },
    setMkdir() {
      this.isMkdir = true;
      let tmp = {
        name: '',
        type: 'dir',
        filetype: 'floder',
        format_size: '0B',
        format_mtime: new Date()
      };
      if (this.fileList[0].name != '') {
        this.fileList.unshift(tmp)
      } else if (this.fileList[0].type != tmp.type) {
        this.fileList.shift()
        this.fileList.unshift(tmp)
      }
    },
    setTouch() {
      this.isTouch = true;
      let tmp = {
        name: '',
        type: 'file',
        filetype: 'document',
        format_size: '0B',
        format_mtime: new Date()
      };
      if (this.fileList[0].name != '') {
        this.fileList.unshift(tmp)
      } else if (this.fileList[0].type != tmp.type) {
        this.fileList.shift()
        this.fileList.unshift(tmp)
      }
    },
    setRename() {
      this.isRename = true;
      this.newFileName = this.currentFile.name;
    },
    setCopy() {
      var that = this;
      that.operaName = 'copy';
      that.showTreeDirFrame = true;
      that.loadingTreeDirList = true;
      that.$axios.get('index/dirTree').then(res => {
        if (res.data.code == 1) {
          that.loadingTreeDirList = false;
          that.treeDirList = res.data.data;
        } else {
          this.$message.error('获取目标文件夹数据失败');
        }
      });
    },
    setMove() {
      var that = this;
      that.operaName = 'move';
      that.showTreeDirFrame = true;
      that.loadingTreeDirList = true;
      that.$axios.get('index/dirTree').then(res => {
        if (res.data.code == 1) {
          that.loadingTreeDirList = false;
          that.treeDirList = res.data.data;
        } else {
          this.$message.error('获取目标文件夹数据失败');
        }
      });
    },
    setShare() {
      this.isShare = true;
    },
    cancleOpera() {
      if (this.isMkdir || this.isTouch) {
        this.fileList.shift();
      }
      this.isMkdir = this.isRename = this.isTouch = false;
      this.newFileName = '';
    },
    rename() {
      let that = this;
      that.$axios.get('opera/rename', {
        params: {
          currentPath: that.currentPath.join('/'),
          current: that.currentFile.name,
          name: that.newFileName
        }
      }).then(res => {
        if (res.data.code == 1) {
          that.currentFile.name = that.newFileName;
          that.isMkdir = that.isRename = that.isTouch = false;
        }
      })
    },
    mkdir() {
      let that = this;
      that.$axios.get('engineering.create/floder', {
        params: {
          currentPath: that.currentPath.join('/'),
          name: that.newFileName
        }
      }).then(res => {
        if (res.data.code == 1) {
          that.currentFile.name = that.newFileName;
          that.isMkdir = that.isRename = that.isTouch = false;
        }
      })
    },
    touch() {
      var that = this;
      that.$axios.get('engineering.create/document', {
        params: {
          currentPath: that.currentPath.join('/'),
          name: that.newFileName
        }
      }).then(res => {
        if (res.data.code == 1) {
          that.currentFile.name = that.newFileName;
          that.isMkdir = that.isRename = that.isTouch = false;
        }
      })
    },
    change(e) {
      //解决el-input不能输入问题
      this.$forceUpdate();
    },
    doOpera() {
      if (this.newFileName == '') {
        this.$message.error('请选择目标目录');
        return;
      }
      var that = this;
      //如果是复制则掉copy否则调move
      that.$axios.post('opera/' + that.operaName + '?currentPath=' + that.currentPath.join('/'), {
        current: that.selectFileNameMaps,
        target: that.newFileName,
      }).then(res => {
        if (res.data.code == 1) {
          that.newFileName = '';
          that.showTreeDirFrame = false;
          that.init(that.currentPath.join('/'));
        }
      })
    },
    download() {
      var that = this, data = {};
      if (that.selectFileNameMaps.length > 1) {
        data.filename = that.selectFileNameMaps
      } else {
        data.filename = that.selectFileNameMaps.shift()
      }

      that.$axios.post('opera/download?currentPath=' + that.currentPath.join('/'), data, {responseType: 'arraybuffer'}).then(res => {
        if (res.status == 200 && !res.data.code) {
          let response = res.data,
              contentDisposition = res.headers['content-disposition'],
              contentType = res.headers['content-type'],
              filename = contentDisposition.split('filename=').pop();

          if (!filename) {
            filename = that.currentFile.name;
          }
          if (!contentType) {
            that.$message.warning('获取文件信息失败，请稍后再试')
            return;
          }

          let blob = new Blob([response], {
            type: contentType
          });

          if ('download' in document.createElement('a')) {
            //支持a标签download的浏览器
            const link = document.createElement('a') //创建a标签
            link.download = filename //a标签添加属性
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            document.body.appendChild(link)
            link.click() //执行下载C
            URL.revokeObjectURL(link.href) //释放url
            document.body.removeChild(link) //释放标签
          } else {
            navigator.msSaveBlob(blob, fileName)
          }
        } else {
          that.$message.warning(!res.data.message ? '文件下载失败，请稍后重试！' : res.data.message);
        }
      })
    },
    share() {
      //TODO:分享
    },
    deleted() {
      var that = this;
      that.loading = true;
      that.$axios.post('opera/delete?currentPath=' + that.currentPath.join('/'), {
        targets: that.selectFileNameMaps
      }).then(res => {
        if (res.data.code == 1) {
          that.fileList.forEach(function (row, index, array) {
            if (that.selectFileNameMaps.indexOf(row.name) > -1) {
              that.fileList.splice(index, 1);
            }
          });
          that.selectFileNameMaps = [];
          that.checkedFiles = [];
          that.currentFile = {};
          that.$emit('listenCheckedFiles', []);
          that.$emit('listenCurrentFile', {});
          that.$emit('listenFileList', that.fileList);
          that.loading = false;
        }
      })
    },
    selectTreeDir(data) {
      //目标文件夹树选中事件
      this.newFileName = data.target;
    },
    preview(item) {
      var that = this;
      this.previewFrame = true;
      if (item.filetype == 'video') {
        item.sources = {
          type: item.mime,
          src: item.link
        };
        item.poster = item.preview;
        item.fluid = true;
      } else if (item.filetype == 'audio') {
        item.title = item.name;
        /*title: 'secret base~君がくれたもの~',
            artist: 'Silent Siren',
            src: 'https://moeplayer.b0.upaiyun.com/aplayer/secretbase.mp3',
            pic: 'https://moeplayer.b0.upaiyun.com/aplayer/secretbase.jpg'*/
        item.src = item.link;
        item.pic = item.preview;
        item.mimi = false;
        item.float = true;
        item.mutex = true;
        // item.theme = '';
      } else if (item.edit) {
        that.editorContent = '';
        that.$axios(item.content).then(res => {
          if (res.data.code == 1) {
            that.editorContent = res.data.data.content;
          }
        });
        console.log(that.editorContent);
      }
      that.previewOptions = item;
      console.log(this.previewOptions, 'options');
      //TODO:预览
    },
    open(item) {
      //TODO:编辑
      console.log(item, 'dbclick');
    },
    closePreviewFrame() {
      this.previewFrame = false;
      this.previewOptions = {};
    },
    doShare() {
      var that = this;
      this.$axios.post('share/set?currentPath=' + that.currentPath.join('/'), {
        files: that.selectFileNameMaps,
        expire: that.shareExpireTime,
      }).then(res => {
        if (res.code == 1) {
          that.shareExpireTime = 0;
          that.isShare = false;
        }
      })
    }
  }
}
</script>

<style scoped>
.el-table__header tr,
.el-table__header th {
  padding: 0;
  height: 40px;
}

.table, .grid {
  height: 100%;
  overflow: hidden;
  overflow-y: auto;
}

.grid-item {
  width: 100%;
}

.background-image {
  width: 120px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  overflow: hidden;
}

.background-image img {
  width: 70%;
}

.text {
  width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center;
}

.el-card .check-area {
  width: 16px;
  position: relative;
  top: -10px;
  left: -5px;
}
</style>